package com.raidpoints.client;

import java.util.ArrayList;
import java.util.Comparator;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.raidpoints.client.AccountPage.GameCell;

public class PointsTable extends Composite{
	CellTable<character> eTable;
	ListDataProvider<character> dataProvider;
	ArrayList<character> flist;
	ListHandler<character> sortHandler;
	SingleSelectionModel<character> selectionModel;
	RaidPoints rp;
	SimplePager simplePager;
	String lastentry;
	TextColumn<character> nameCol;
	CheckBox cwow,cswtor;
	
	public PointsTable(RaidPoints mrp) {
		rp = mrp;
		lastentry = "";
		flist = new ArrayList<character>();
		dataProvider = new ListDataProvider<character>();
		sortHandler = new ListHandler<character>(dataProvider.getList());
		selectionModel = new SingleSelectionModel<character>();
		
		DockLayoutPanel layoutPanel = new DockLayoutPanel(Unit.EM);
		initWidget(layoutPanel);
		eTable = new CellTable<character>();
		eTable.setPageSize(100);
		eTable.setSize("100%", "100%");
		eTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		ScrollPanel scrollpan = new ScrollPanel();
		scrollpan.add(eTable);
		
		dataProvider.addDataDisplay(eTable);
		eTable.addColumnSortHandler(sortHandler);
		eTable.setSelectionModel(selectionModel);
		
		HorizontalPanel hpan = new HorizontalPanel();
		
		SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
		simplePager = new SimplePager(TextLocation.CENTER,pagerResources,false,0,true);
		simplePager.setDisplay(eTable);
		hpan.add(simplePager);
	
		cwow = new CheckBox("WoW"); cswtor = new CheckBox("SWTOR");
		cwow.setValue(true); cswtor.setValue(true);
		final TextBox searchBox = new TextBox();
		final Button searchButton = new Button("Search");
		hpan.setSpacing(1);
		hpan.add(cwow); hpan.add(cswtor);
		hpan.add(searchBox); hpan.add(searchButton);
		searchButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
//				String csearch = searchBox.getText();	
//				for(character c : dataProvider.getList()){
//					if(c.name.equalsIgnoreCase(csearch)){
//						rp.ViewChar(c);
//						break;
//					}
//				}
//				searchBox.setText("");
				if(dataProvider.getList().size() == 1){
					rp.ViewChar(dataProvider.getList().get(0));
				}
			}
		});
		
//		searchBox.addKeyPressHandler(new KeyPressHandler(){
//			public void onKeyPress(KeyPressEvent event) {
//				if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
//					searchButton.click();
//				}
//			}
//			
//		});
		
		searchBox.addKeyUpHandler(new KeyUpHandler(){
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
					searchButton.click();
					return;
				}
				if(!searchBox.getText().equals(lastentry)){
					lastentry = searchBox.getText();
					Populate();
//					dataProvider.getList().clear();
//					lastentry = searchBox.getText();
//					if(lastentry.length() >= 1) {
//						for(character c : flist){
//							if(c.name.toLowerCase().startsWith(lastentry.toLowerCase())) dataProvider.getList().add(c);
//						}
//					}
//					else {
//						dataProvider.getList().addAll(flist);
//					}
//					eTable.setRowCount(dataProvider.getList().size());
//					simplePager.firstPage();
//					ColumnSortEvent.fire(eTable,eTable.getColumnSortList());
				}

			}
		});
		
		cwow.addValueChangeHandler(new ValueChangeHandler<Boolean>(){
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				Populate();				
			}
		});
		
		cswtor.addValueChangeHandler(new ValueChangeHandler<Boolean>(){
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				Populate();				
			}
		});
		
		Button listButton = new Button("Get EasyLOP points");
		hpan.add(listButton);
		
		layoutPanel.addNorth(hpan, 3);
		layoutPanel.add(scrollpan);
		
		listButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				rp.GetPointsList();
			}
		});
		
		Column<character,character> gameCol = new Column<character,character>(new GameCell()){

			@Override
			public character getValue(character object) {
				return object;
			}
			
		};
		eTable.addColumn(gameCol);
		eTable.setColumnWidth(gameCol, "16px");
		
		nameCol = new TextColumn<character>(){
			@Override
			public String getValue(character object) {
				return object.name;
			}
			
		};
		nameCol.setSortable(true);
		eTable.addColumn(nameCol,"Name");
		
		
		TextColumn<character> pointsCol = new TextColumn<character>(){
			@Override
			public String getValue(character object) {
				return Double.toString(object.points);
			}
			
		};
		pointsCol.setSortable(true);
		eTable.addColumn(pointsCol,"Points");
		
		TextColumn<character> raCol = new TextColumn<character>(){
			@Override
			public String getValue(character object) {
				return Integer.toString(object.subraid);
			}
		};
		raCol.setSortable(true);
		eTable.addColumn(raCol,"Raids Attended");
		
		TextColumn<character> iwCol = new TextColumn<character>(){
			@Override
			public String getValue(character object) {
				return Integer.toString(object.ngsid);
			}
		};
		iwCol.setSortable(true);
		eTable.addColumn(iwCol,"Items Won");
		
		ListHandler<character> columnSortHandler = new ListHandler<character>(dataProvider.getList());
		columnSortHandler.setComparator(nameCol, new Comparator<character>(){
			@Override
			public int compare(character arg0, character arg1) {
				if(arg0 == arg1) return 0;
				
				if(arg0 != null){
					return (arg1 != null) ? arg0.name.compareTo(arg1.name) : 1;
				}
				return -1;
			}
		});
		
		columnSortHandler.setComparator(pointsCol, new Comparator<character>(){
			@Override
			public int compare(character arg0, character arg1) {
				if(arg0 == arg1) return 0;
				
				if(arg0 != null){
					if(arg1 == null) return 1;
					else if(arg0.points == arg1.points) return 0;
					else if(arg0.points > arg1.points) return 1;
					else return -1;
				}
				return -1;
			}
		});
		
		columnSortHandler.setComparator(raCol, new Comparator<character>(){
			@Override
			public int compare(character arg0, character arg1) {
				if(arg0 == arg1) return 0;
				
				if(arg0 != null){
					if(arg1 == null) return 1;
					else if(arg0.subraid == arg1.subraid) return 0;
					else if(arg0.subraid > arg1.subraid) return 1;
					else return -1;
				}
				return -1;
			}
		});
		
		columnSortHandler.setComparator(iwCol, new Comparator<character>(){
			@Override
			public int compare(character arg0, character arg1) {
				if(arg0 == arg1) return 0;
				
				if(arg0 != null){
					if(arg1 == null) return 1;
					else if(arg0.ngsid == arg1.ngsid) return 0;
					else if(arg0.ngsid > arg1.ngsid) return 1;
					else return -1;
				}
				return -1;
			}
		});
		
		
		eTable.addColumnSortHandler(columnSortHandler);
	
				
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler(){
			public void onSelectionChange(SelectionChangeEvent event) {
				character selected = selectionModel.getSelectedObject();
				if(selected != null){
					rp.ViewChar(selected);
					selectionModel.setSelected(selected,false);
				}	
				
			}	
		});
		
		UpdatePoints();
	}
	
	public void Populate(){
		Populate(true);
	}
	
	public void Populate(boolean fire){
		dataProvider.getList().clear();
		int ll = lastentry.length();
		for(character c : flist){
			if(c.gid == 1 && !cwow.getValue()) continue;
			if(c.gid == 2 && !cswtor.getValue()) continue;
			if(ll >=1 && !c.name.toLowerCase().startsWith(lastentry.toLowerCase())) continue;
			dataProvider.getList().add(c);
		}
		
		eTable.setRowCount(dataProvider.getList().size());
		simplePager.firstPage();
		if(fire) ColumnSortEvent.fire(eTable,eTable.getColumnSortList());
	}
	
	
	public void UpdatePoints(){
		AsyncCallback<ArrayList<character>> pointsCallback = new AsyncCallback<ArrayList<character>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(ArrayList<character> result) {
				flist.clear();
				flist.addAll(result);
				Populate(false);
//				dataProvider.getList().clear();
//				dataProvider.getList().addAll(result);
//				
//				eTable.setRowCount(result.size());
//				simplePager.firstPage();
				eTable.getColumnSortList().push(nameCol);
			}
			
		};
		
		rp.rpsvc.GetAllChars(pointsCallback);
	}
	
	public class GameCell extends AbstractCell<character>{

		@Override
		public void render(com.google.gwt.cell.client.Cell.Context context,character value, SafeHtmlBuilder sb) {
			sb.appendHtmlConstant("<img src=\"cicons/" + (value.gid == 1 ? "wow" : "swtor") + ".png\" width=\"20\" height=\"20\">");			
		}
		
	}
}
